package com.gdue.filter;

import com.alibaba.fastjson.JSON;
import com.gdue.commons.BaseContext;
import com.gdue.commons.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher  PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest  request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        //1.获取本次请求的uri
        String requestURI = request.getRequestURI();
        String[]    uris=new String[]{
                "/employee/login",
                "/employee/logout"
              //个人感觉静态资源路径也不要放行比较好
                //拦截了的话会导致js无法发送接收
                ,
                "/backend/**",
                "/front/**"
        };
        //2.判断本次请求是否需要处理
        boolean check = check(uris, requestURI);
        //3.如果不需要处理，直接放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        //4.判断登录状态，如果已登录，直接放行
        Object employee = request.getSession().getAttribute("employee");
        if (!(employee==null)){
            filterChain.doFilter(request,response);
            return;
        }
        //如果未登录，返回登录页面,通过输出流方式向客户端页面响应数据（根据前端要的数据去响应）
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean  check(String[] uris,String requestUri){
        for ( String  uri:uris) {
            boolean match = PATH_MATCHER.match(uri, requestUri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
